package com.leyou.auth.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.auth.config.OssProperties;
import com.leyou.auth.dto.AliOssSignatureDTO;
import com.leyou.auth.service.AliAuthService;
import com.leyou.common.exceptions.LyException;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author 虎哥
 */
@Service
public class AliAuthServiceImpl implements AliAuthService {

    private final OSS ossClient;
    private final OssProperties prop;

    public AliAuthServiceImpl(OSS ossClient, OssProperties prop) {
        this.ossClient = ossClient;
        this.prop = prop;
    }

    @Override
    public AliOssSignatureDTO getOssSignature() {
        try {
            // 生成的签名的过期时间，单位是s
            long expireTime = prop.getExpireTime();
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);

            // 大小限制
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, prop.getMaxFileSize());
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, prop.getDir());

            // 生成策略字符串
            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            // 利用base64算法对策略字符串加密
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);

            // 生成签名
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            return AliOssSignatureDTO.of(
                    prop.getAccessKeyId(),
                    prop.getHost(),
                    encodedPolicy, postSignature,
                    expireEndTime,
                    prop.getDir());

        } catch (Exception e) {
            throw new LyException(500, e);
        }
    }
}
